package cn.ctvonline.android.kaopu.activity;

import android.animation.ValueAnimator;
import android.os.Bundle;
import android.util.Log;
import android.view.MotionEvent;
import android.view.VelocityTracker;
import android.view.View;
import android.view.View.OnTouchListener;
import android.view.ViewConfiguration;
import android.view.ViewGroup;
import android.view.animation.AccelerateInterpolator;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import butterknife.Bind;
import butterknife.ButterKnife;
import cn.ctvonline.android.kaopu.R;
import cn.ctvonline.android.kaopu.base.BaseAppCompatActivity;
import cn.ctvonline.android.kaopu.base.util.WindowUtil;

/**
 * Created by dujian on 15/12/21.
 */
public class SwiperActivity extends BaseAppCompatActivity {
    static final String TAG = "SwiperActivity";
    private OnSwipeListener onSwipeListener;
    private ContentTouchListener onContentTouchListener;
    @Bind(R.id.above_swiper_ll)
    LinearLayout swipeLl;
    @Bind(R.id.blow_container_rl)
    RelativeLayout containerRl;
    @Bind(R.id.swipe_demo_tv)
    TextView swipeTv;
    View rootView;
    boolean dragable = true;
    int maxVelocity = 1000;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_swiper_demo);
        rootView = ((ViewGroup) getWindow().getDecorView()).getChildAt(0);
        initViews();
        maxVelocity = ViewConfiguration.get(this).getScaledMaximumFlingVelocity();
    }

    private void initViews() {
        ButterKnife.bind(this);
//        containerRl.setFocusable(false);
//        containerRl.setEnabled(false);
//        containerRl.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                ToastUtil.show(getApplicationContext(), "container clicked");
//            }
//        });
//        containerRl.removeAllViews();
//        containerRl.addView(firstView);
//        swipeLl.setVisibility(View.GONE);
//        swipeLl.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//
//            }
//        });
//        swipeLl.setOnTouchListener(new OnTouchListener() {
//            @Override
//            public boolean onTouch(View v, MotionEvent event) {
//                requestVelocityTracker(event);
//                final VelocityTracker verTracker = vTracker;
//                int lastDeltaX = 0;
//                int pointerID = 0;
//                switch (event.getAction()) {
//                    case MotionEvent.ACTION_DOWN: {
//                        dragable = true;
//                        Log.i(TAG, "rootView onTouch action_down");
//                        startX = (int) event.getRawX();
//                        startY = (int) event.getRawY();
//                        pointerID = event.getPointerId(0);
//                    }
//                    break;
//                    case MotionEvent.ACTION_MOVE: {
//                        verTracker.computeCurrentVelocity(1000, maxVelocity);
//                        float speedX = verTracker.getXVelocity(pointerID);
//                        if (isTransAniming || !dragable) {
//                            break;
//                        }
//                        int deltaX = (int) event.getRawX() - startX;
//                        int deltaY = (int) event.getRawY() - startY;
//                        if (Math.abs(deltaX - lastDeltaX) < 10) {
//                            break;
//                        }
//                        if (Math.abs(deltaY) > Math.abs(deltaX) && deltaX > 10) {
//                            dragable = false;
//                            Log.i(TAG, "move break isTransAniming=" + isTransAniming + ", dragable=" + dragable);
//                            break;
//                        }
//                        lastDeltaX = deltaX;
//                        float translation = swipeLl.getTranslationX();
//                        Log.i(TAG, "rootView onTouch action_move translation = " + translation);
//                        if (translation >= 0 && translation < WindowUtil.getScreenWidth(getApplicationContext())
//                                && Math.abs(deltaX) > Math.abs(deltaY)) {
//                            swipeLl.setTranslationX(deltaX);
//                        }
//                        Log.i(TAG, "speed of x is [" + speedX + "]");
//                        if (speedX > 2500) {
//                            playTranslationAnim(swipeLl, WindowUtil.getScreenWidth(getApplicationContext()));
//                            dragable = false;
//                            break;
//                        }
//                        Log.i(TAG, "move isTransAniming=" + isTransAniming + ", dragable=" + dragable);
//                    }
//                    break;
//                    case MotionEvent.ACTION_CANCEL:
//                    case MotionEvent.ACTION_UP: {
//                        dragable = true;
//                        float translation = swipeLl.getTranslationX();
//                        if (translation >= WindowUtil.getScreenWidth(getApplicationContext()) / 2
//                                && translation < WindowUtil.getScreenWidth(getApplicationContext())) {
//                            playTranslationAnim(swipeLl, WindowUtil.getScreenWidth(getApplicationContext()));
//                        } else if (translation > 0 && translation < WindowUtil.getScreenWidth(getApplicationContext()) / 2) {
//                            playTranslationAnim(swipeLl, 0);
//                        }
//                        Log.i(TAG, "up or cancel isTransAniming=" + isTransAniming + ", dragable=" + dragable);
//                    }
//                    break;
//                }
//                return false;
//            }
//        });
    }

    boolean isTransAniming = false;

    public void playTranslationAnim(final View view, final float endTranslationX) {
        isTransAniming = true;
        ValueAnimator animator = ValueAnimator.ofFloat(view.getTranslationX(), endTranslationX);
        animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
                float value = (float) animation.getAnimatedValue();
                view.setTranslationX(value);
                if (value == endTranslationX) {
                    isTransAniming = false;
                }
                if (value == WindowUtil.getScreenWidth(getApplicationContext())) {
                    onBackPressed();
                }
            }
        });
        animator.setDuration(300);
        animator.setInterpolator(new AccelerateInterpolator());
        animator.start();
    }

    private int startX, startY;

    @Override
    protected void onResume() {
        super.onResume();
    }

    class ContentTouchListener implements OnTouchListener {
        @Override
        public boolean onTouch(View v, MotionEvent event) {
            switch (event.getAction()) {
                case MotionEvent.ACTION_DOWN: {
                    Log.i(TAG, "rootView onTouch action_down");
                    startX = (int) event.getX();
                    startY = (int) event.getY();
                }
                break;
                case MotionEvent.ACTION_MOVE: {
                    int deltaX = (int) event.getX() - startX;
                    int deltaY = (int) event.getY() - startY;
                    float translation = swipeLl.getTranslationX();
                    Log.i(TAG, "rootView onTouch action_move translation = " + translation);
                    if (translation >= 0 && translation < WindowUtil.getScreenWidth(getApplicationContext())
                            && Math.abs(deltaX) > Math.abs(deltaY)) {
                        swipeLl.setTranslationX(deltaX);
                    }
                }
                break;
                case MotionEvent.ACTION_CANCEL:
                case MotionEvent.ACTION_UP: {
                    releaseVelocityTracker();
                    float translation = swipeLl.getTranslationX();
                    if (translation >= WindowUtil.getScreenWidth(getApplicationContext()) / 2
                            && translation < WindowUtil.getScreenWidth(getApplicationContext())) {
                        playTranslationAnim(swipeLl, WindowUtil.getScreenWidth(getApplicationContext()));
                    } else if (translation >= 0 && translation < WindowUtil.getScreenWidth(getApplicationContext()) / 2) {
                        playTranslationAnim(swipeLl, 0);
                    }
                }
                break;
            }
            return true;
        }
    }

    private VelocityTracker vTracker;

    private synchronized void requestVelocityTracker(MotionEvent event) {
        if (null == vTracker) {
            vTracker = VelocityTracker.obtain();
        }
        vTracker.addMovement(event);
    }

    private void releaseVelocityTracker() {
        if (null != vTracker) {
            vTracker.clear();
            vTracker.recycle();
            vTracker = null;
        }
    }

    public interface OnSwipeListener {
        void onSwiper(int distance);
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
        overridePendingTransition(0, 0);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

    @Override
    protected String generatePageName() {
        return "PageName is SwiperActivity";
    }
}
